import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.text.Collator;
import java.text.NumberFormat;
import java.util.ArrayList;

public class PreferencesDialog extends JDialog 
{
	public PreferencesDialog(JFrame mainFrame)
	{
		super(mainFrame,Resources.getString("preferences"),true);
		init();
		JPanel mainPanel = new JPanel(new BorderLayout());
		JPanel centerPanel = new JPanel();
		centerPanel.add(this.getSomaSportEditorPanel(),BorderLayout.CENTER);
		mainPanel.add(centerPanel,BorderLayout.CENTER);
		mainPanel.add(this.getBottomPanel(),BorderLayout.SOUTH);
		this.add(mainPanel);
		this.setSize(800,600);
	}
	private void init()
	{
		//currentIndex = 0;
		SomatotypeAthletes[] sportList = SomatotypeIO.getSomatotypeList();
		sportSoma = new ArrayList<SomatotypeAthletes>(sportList.length+1);
		sportSoma.add(0, new SomatotypeAthletes());
		for(int i = 0; i < sportList.length; i++)
		{
			sportSoma.add(sportList[i]);
		}
	}
	private JPanel getSomaSportEditorPanel()
	{
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel,BoxLayout.X_AXIS));
		JPanel adminButtonsPanel = new JPanel();
		adminButtonsPanel.setLayout(new GridBagLayout());//BoxLayout(adminButtonsPanel,BoxLayout.Y_AXIS));
		JPanel sportComboPanel = new JPanel();
		sportComboPanel.setLayout(new GridBagLayout());//BoxLayout(sportComboPanel,BoxLayout.X_AXIS));
		JPanel panelValues = new JPanel();
		panelValues.setLayout(new GridLayout(4,3));//BoxLayout(panelValues,BoxLayout.Y_AXIS));
		Border etched = BorderFactory.createEmptyBorder();
        Border titled = BorderFactory.createTitledBorder(
            etched, 
            Resources.getString("somatotypeAthletes"),
            TitledBorder.LEFT, 
            TitledBorder.TOP, 
            Resources.getFont(Resources.FONT_TYPE.BORDER)
        );
        panel.setBorder(titled);
        JButton addButton = new JButton(Resources.getString("add"));
        JButton editButton = new JButton(Resources.getString("edit"));
        JButton deleteButton = new JButton(Resources.getString("delete"));
        JLabel sportLabel = new JLabel(Resources.getString("sport"));
        ArrayList <String> sportsName = SomatotypeIO.getSportsList();
        sportsName.add(0,"");
		sportCombo = Components.getComboBox(sportsName.toArray());
		JLabel maleLabel = new JLabel(Resources.getString("male"));
		JLabel femaleLabel = new JLabel(Resources.getString("female"));
		JLabel endoLabel = new JLabel(Resources.getString("endomorphy"));
		JLabel mesoLabel = new JLabel(Resources.getString("mesomorphy"));
		JLabel ectoLabel = new JLabel(Resources.getString("ectomorphy"));
		final JFormattedTextField endoMale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
		final JFormattedTextField mesoMale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
		final JFormattedTextField ectoMale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
		final JFormattedTextField endoFemale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
		final JFormattedTextField mesoFemale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
		final JFormattedTextField ectoFemale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
		addButton.addActionListener(new
			ActionListener()
			{
				public void actionPerformed(ActionEvent e) 
				{
					SomatotypeAthletes soma = new SomatotypeAthletes();
					boolean isOk = false;
					ChangeDialog dialog = new ChangeDialog(soma);
					dialog.setLocation(Elite.getCenteringDim(PreferencesDialog.this, dialog.getSize()));
					do
					{
						dialog.setVisible(true);
						if(dialog.isChanged())
						{
							soma = dialog.getNewValues();
							if(!addSportSoma(soma))
								JOptionPane.showMessageDialog(
										PreferencesDialog.this, 
										Resources.getString("nameRepeat"), 
										Resources.getString("warning"), 
										JOptionPane.WARNING_MESSAGE);
							else
								isOk = true;
						}
						else
							isOk = true;
					}while(isOk != true);
				}
			}
		);
		editButton.addActionListener(new
				ActionListener()
				{
					public void actionPerformed(ActionEvent e) 
					{
						int index = sportCombo.getSelectedIndex();
						if(index == 0)
							return;
						SomatotypeAthletes soma = sportSoma.get(index);
						SomatotypeAthletes aux = sportSoma.get(index);
						sportSoma.remove(index);
						sportCombo.removeItemAt(index);
						boolean isOk = false;
						ChangeDialog dialog = new ChangeDialog(soma);
						dialog.setLocation(Elite.getCenteringDim(PreferencesDialog.this, dialog.getSize()));
						do
						{
							dialog.setVisible(true);
							if(dialog.isChanged())
							{
								soma = dialog.getNewValues();
								if(!addSportSoma(soma))
									JOptionPane.showMessageDialog(
											PreferencesDialog.this, 
											Resources.getString("nameRepeat"), 
											Resources.getString("warning"), 
											JOptionPane.WARNING_MESSAGE);
								else
									isOk = true;
							}
							else
								isOk = addSportSoma(aux);
						}while(isOk != true);
					}
				}
		);
		deleteButton.addActionListener(new
				ActionListener()
				{
					public void actionPerformed(ActionEvent e) 
					{
						int index = sportCombo.getSelectedIndex();
						if(index == 0)
							return;
						SomatotypeAthletes soma = sportSoma.get(index);
						int answer = JOptionPane.showConfirmDialog(
								PreferencesDialog.this, 
								Resources.getString("deleteDialog"), 
								Resources.getString("delete"), 
								JOptionPane.YES_NO_OPTION, 
								JOptionPane.QUESTION_MESSAGE);
						if(answer == JOptionPane.YES_OPTION)
						{
							sportSoma.remove(index);
							sportCombo.removeItemAt(index);
						}
					}
				}
		);
		sportCombo.addItemListener(new
			ItemListener()
			{
				public void itemStateChanged(ItemEvent e) 
				{
					JComboBox<String> aux = (JComboBox) e.getSource();
					if(aux.getSelectedIndex() < 0)
						return;
					if(aux.getSelectedIndex() == 0)
					{
						endoMale.setText("");
						mesoMale.setText("");
						ectoMale.setText("");
						endoFemale.setText("");
						mesoFemale.setText("");
						ectoFemale.setText("");
					}else
					{
						SomatotypeAthletes somaSelect = sportSoma.get(aux.getSelectedIndex());
						Somatotype soma = somaSelect.getMaleSomatotype();
						endoMale.setValue(soma.getEndo());
						mesoMale.setValue(soma.getMeso());
						ectoMale.setValue(soma.getEcto());
						soma = somaSelect.getFemaleSomatotype();
						endoFemale.setValue(soma.getEndo());
						mesoFemale.setValue(soma.getMeso());
						ectoFemale.setValue(soma.getEcto());
					}
				}
			}
		);
		GridBagConstraints constraints = new 
			GridBagConstraints(
				0, 
				0, 
				1, 
				1, 
				1, 
				1, 
				GridBagConstraints.CENTER, 
				GridBagConstraints.HORIZONTAL, 
				new Insets(0,0,0,10), 
				0, 
				0);
		adminButtonsPanel.add(addButton,constraints);
		constraints.gridy = 1;
		adminButtonsPanel.add(editButton,constraints);
		constraints.gridy = 2;
		adminButtonsPanel.add(deleteButton,constraints);
		constraints.gridy = 0;
		sportComboPanel.add(sportLabel,constraints);
		constraints.gridx = 1;
		sportComboPanel.add(sportCombo,constraints);
		panelValues.add(new JPanel());
		panelValues.add(maleLabel);
		panelValues.add(femaleLabel);
		panelValues.add(endoLabel);
		panelValues.add(endoMale);
		panelValues.add(endoFemale);
		panelValues.add(mesoLabel);
		panelValues.add(mesoMale);
		panelValues.add(mesoFemale);
		panelValues.add(ectoLabel);
		panelValues.add(ectoMale);
		panelValues.add(ectoFemale);
		panel.add(sportComboPanel);
		panel.add(panelValues);
		panel.add(adminButtonsPanel);
		endoMale.setEditable(false);
		mesoMale.setEditable(false);
		ectoMale.setEditable(false);
		endoFemale.setEditable(false);
		mesoFemale.setEditable(false);
		ectoFemale.setEditable(false);
		endoMale.setFocusable(false);
		mesoMale.setFocusable(false);
		ectoMale.setFocusable(false);
		endoFemale.setFocusable(false);
		mesoFemale.setFocusable(false);
		ectoFemale.setFocusable(false);
		endoMale.setText("");
		mesoMale.setText("");
		ectoMale.setText("");
		endoFemale.setText("");
		mesoFemale.setText("");
		ectoFemale.setText("");
		return panel;
	}
	private JPanel getBottomPanel()
	{
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		JButton okButton = new JButton(Resources.getString("ok"));
		JButton applyButton = new JButton(Resources.getString("apply"));
		JButton cancelButton = new JButton(Resources.getString("cancel"));
		okButton.setFont(Resources.getFont(Resources.FONT_TYPE.LABELS));
		applyButton.setFont(Resources.getFont(Resources.FONT_TYPE.LABELS));
		cancelButton.setFont(Resources.getFont(Resources.FONT_TYPE.LABELS));
		okButton.addActionListener(new
				ActionListener()
				{
					public void actionPerformed(ActionEvent e) 
					{
						SomatotypeIO.deleteCopy();
						setVisible(false);
					}
				}
			);
		applyButton.addActionListener(new
				ActionListener()
				{
					public void actionPerformed(ActionEvent e) 
					{
						SomatotypeIO.createCopy();
						SomatotypeAthletes[] newSomaList = new SomatotypeAthletes[sportSoma.size()-1];
						for(int i = 0; i < sportSoma.size()-1; i++)
							newSomaList[i] = sportSoma.get(i+1);
						SomatotypeIO.setSomatotypeList(newSomaList);
						//setVisible(false);
					}
				}
			);
		cancelButton.addActionListener(new
				ActionListener()
				{
					public void actionPerformed(ActionEvent e) 
					{
						SomatotypeIO.restoreFile();
						SomatotypeIO.deleteCopy();
						setVisible(false);
					}
				}
			);
		panel.add(okButton);
		panel.add(applyButton);
		panel.add(cancelButton);
		return panel;
	}
	private boolean addSportSoma(SomatotypeAthletes soma)
	{
		int size = sportSoma.size();
		int index = 1;
		Collator collator = Collator.getInstance(Resources.getLocale());
		collator.setStrength(Collator.PRIMARY);
		for(int i = 0; i < size; i++)
		{
			if(collator.equals(sportSoma.get(i).getName(), soma.getName()))//sportSoma.get(i).getName().toLowerCase().equals(soma.getName().toLowerCase()))
				return false;
			if(collator.compare(soma.getName(), sportSoma.get(i).getName()) > 0)//soma.getName().toLowerCase().compareTo(sportSoma.get(i).getName().toLowerCase()) > 0)
				index = i+1;
		}
		sportSoma.add(index, soma);
		sportCombo.insertItemAt(soma.getName(), index);
		sportCombo.setSelectedIndex(index);
		return true;
	}
	private class ChangeDialog extends JDialog
	{
		public ChangeDialog()
		{
			super(PreferencesDialog.this,Resources.getString("add"),true);
			init();
		}
		public ChangeDialog(SomatotypeAthletes sportSoma)
		{
			super(PreferencesDialog.this,Resources.getString("edit"),true);
			init();
			setValues(sportSoma);
		}
		public boolean isChanged()
		{
			return changed;
		}
		public SomatotypeAthletes getNewValues()
		{
			SomatotypeAthletes sportSoma = new SomatotypeAthletes();
			sportSoma.setName(nameField.getText());
			Somatotype maleSoma_ =  new Somatotype();
			Somatotype femaleSoma_ =  new Somatotype();
			maleSoma_.setEndo(((Number)endoMale.getValue()).floatValue());
			maleSoma_.setEcto(((Number)ectoMale.getValue()).floatValue());
			maleSoma_.setMeso(((Number)mesoMale.getValue()).floatValue());
			femaleSoma_.setEndo(((Number)endoFemale.getValue()).floatValue());
			femaleSoma_.setEcto(((Number)ectoFemale.getValue()).floatValue());
			femaleSoma_.setMeso(((Number)mesoFemale.getValue()).floatValue());
			sportSoma.setMaleSoma(maleSoma_);
			sportSoma.setFemaleSoma(femaleSoma_);
			return sportSoma;
		}
		private void init()
		{
			changed = false;
			JPanel panel = new JPanel(new BorderLayout());
			JPanel northPanel = new JPanel();
			JPanel centerPanel = new JPanel(new GridLayout(4,3));
			JPanel southPanel = new JPanel();
			JLabel nameLabel = new JLabel(Resources.getString("sport"));
			JLabel maleLabel = new JLabel(Resources.getString("male"));
			JLabel femaleLabel = new JLabel(Resources.getString("female"));
			JLabel endoLabel = new JLabel(Resources.getString("endomorphy"));
			JLabel mesoLabel = new JLabel(Resources.getString("mesomorphy"));
			JLabel ectoLabel = new JLabel(Resources.getString("ectomorphy"));
			nameField = Components.getTextField(); 
			endoMale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
			mesoMale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
			ectoMale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
			endoFemale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
			mesoFemale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
			ectoFemale = Components.getFormattedTextField(NumberFormat.getNumberInstance());
    		JButton acceptButton = new JButton(Resources.getString("accept"));
    		JButton cancelButton = new JButton(Resources.getString("cancel"));
    		acceptButton.addActionListener(new
    				ActionListener()
    				{
    					public void actionPerformed(ActionEvent e) 
    					{
    						changed = true;
    						setVisible(false);
    					}
    				}
    			);
    		cancelButton.addActionListener(new
    				ActionListener()
    				{
    					public void actionPerformed(ActionEvent e) 
    					{
    						changed = false;
    						setVisible(false);
    					}
    				}
    			);
    		centerPanel.add(new JPanel());
    		centerPanel.add(maleLabel);
    		centerPanel.add(femaleLabel);
    		centerPanel.add(endoLabel);
    		centerPanel.add(endoMale);
    		centerPanel.add(endoFemale);
    		centerPanel.add(mesoLabel);
    		centerPanel.add(mesoMale);
    		centerPanel.add(mesoFemale);
    		centerPanel.add(ectoLabel);
    		centerPanel.add(ectoMale);
    		centerPanel.add(ectoFemale);
    		northPanel.add(nameLabel);
    		northPanel.add(nameField);
    		southPanel.add(acceptButton);
    		southPanel.add(cancelButton);
    		panel.add(northPanel,BorderLayout.NORTH);
    		panel.add(centerPanel,BorderLayout.CENTER);
    		panel.add(southPanel,BorderLayout.SOUTH);
    		this.add(panel);
    		this.setSize(300,200);
		}
		private void setValues(SomatotypeAthletes sportSoma)
		{
			nameField.setText(sportSoma.getName());
			Somatotype male = sportSoma.getMaleSomatotype();
			Somatotype female = sportSoma.getFemaleSomatotype();
			endoMale.setValue(male.getEndo());
			mesoMale.setValue(male.getMeso());
			ectoMale.setValue(male.getEcto());
			endoFemale.setValue(female.getEndo());
			mesoFemale.setValue(female.getMeso());
			ectoFemale.setValue(female.getEcto());
		}
		private JTextField nameField; 
		private JFormattedTextField endoMale;
		private JFormattedTextField mesoMale;
		private JFormattedTextField ectoMale;
		private JFormattedTextField endoFemale;
		private JFormattedTextField mesoFemale;
		private JFormattedTextField ectoFemale;
		private boolean changed;
	}
	/*private class Change
	{
		public Change(TASKS task_,String name_)
		{
			name = name_;
			task = task_;
		}
		public String getName()
		{
			return name;
		}
		public TASKS getTask()
		{
			return task;
		}
		private String name;
		private TASKS task;
	}*/
	private static enum TASKS {EDIT,ADD,DELETE;}
	private ArrayList<SomatotypeAthletes> sportSoma;
	private JComboBox<String> sportCombo;
	//private int currentIndex;
	//private ArrayList<Change> changes;
}